package com.ruoyi.health.report.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ChenYF
 * @date 2025-09-03 9:05
 */
public class AesUtil {
    // 偏移量
    private static final String PADDING_KEY = "1234567812345678";
    private static final Charset utf8 = StandardCharsets.UTF_8;


    /**
     * 加密
     *
     * @param content   需要加密的内容
     * @param secretKey 密钥
     * @return
     */
    public static String encrypt(String content, SecretKey secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(PADDING_KEY.getBytes(utf8)));

            byte[] byteContent = content.getBytes(utf8);
            byte[] result = cipher.doFinal(byteContent);
            return new BASE64Encoder().encode(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("加密过程报错----- " + e.getMessage());
        }
        return null;
    }

    /**
     * AES（256）解密
     *
     * @param content   待解密内容
     * @param secretKey 解密密钥
     * @return 解密之后
     * @throws Exception
     */
    public static String decrypt(String content, SecretKey secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(PADDING_KEY.getBytes(utf8)));
            byte[] result = cipher.doFinal(new BASE64Decoder().decodeBuffer(content));
            return new String(result, utf8); // 解密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String removeIllegalCharacters(String jsonString) {
        // 定义正则表达式，匹配控制字符和其他非法字符
        String illegalCharactersRegex = "[\\x00-\\x1F]";
        Pattern pattern = Pattern.compile(illegalCharactersRegex);
        Matcher matcher = pattern.matcher(jsonString);

        // 使用空字符串替换非法字符
        String jsonStringWithoutIllegalChars = matcher.replaceAll("");

        return jsonStringWithoutIllegalChars;
    }
}
